<template>
    <div :style="`min-height: ${pageMinHeight}px`">
        <div>
            <a-card style="width: 100%">
                <a-form :form="userSearch"  labelAlign="right" layout="horizontal">
                    <a-row>
                        <a-col :span="2">
                            <a-button type="primary" icon="plus" @click="visible = true">
                                新增
                            </a-button>
                            <a-modal :visible="visible" title="新增成员" @ok="handleOk" @cancel="handleCancel">
                                <a-form :form="user">
                                    <a-form-item label="姓名" name="name">
                                        <a-input v-model="user.name"
                                            v-decorator="['name', { rules: [{ required: true, message: 'Please input your name!' }] }]" />
                                    </a-form-item>

                                    <a-form-item label="年龄" name="age" rules="required|integer">
                                        <a-input-number v-model="user.identity"
                                            v-decorator="['age', { rules: [{ required: true, message: 'Please input your age!' }] }]" />
                                    </a-form-item>

                                    <a-form-item label="手机号" name="phone" rules="required|phone">
                                        <a-input v-model="user.phone"
                                            v-decorator="['phone', { rules: [{ required: true, message: 'Please input your phone!' }] }]" />
                                    </a-form-item>

                                    <a-form-item label="个人介绍" name="introduction" rules="required">
                                        <a-textarea v-model="user.introduction" />
                                    </a-form-item>
                                    <a-form-item label="选择身份" name="identity" rules="required">
                                        <a-select ref="select" v-model="user.role" style="width: 120px"
                                            v-decorator="['role', { rules: [{ required: true, message: 'Please input your role!' }] }]"
                                            @change="ChangeIdentity">
                                            <a-select-option value="admin">管理员</a-select-option>
                                            <a-select-option value="user">用户</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                    <a-form-item label="上传头像" name="avatar" rules="required">
                                        <a-upload name="avatar" list-type="picture-card" class="avatar-uploader"
                                            :show-upload-list="false"
                                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                            :before-upload="beforeUpload" @change="avatarChange">
                                            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
                                            <div v-else>
                                                <a-icon :type="loading ? 'loading' : 'plus'" />
                                                <div class="ant-upload-text">
                                                    Upload
                                                </div>
                                            </div>
                                        </a-upload>
                                    </a-form-item>
                                </a-form>
                            </a-modal>
                        </a-col>
                        <a-col :span="6" :offset="2">
                            <a-form-item style="width: 240px" name="role">
                                <a-select default-value="3" v-model="userSearch.role" >
                                    <a-select-option value="3" disabled>
                                        根据身份搜索
                                    </a-select-option>
                                    <a-select-option value="admin">
                                        管理员
                                    </a-select-option>
                                    <a-select-option value="user">
                                        用户
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="6" :offset="2">
                            <a-form-item style="width: 240px" name="name">
                                <a-input placeholder="根据名称 搜索" v-model="userSearch.name" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="1" :offset="1">
                            <a-button type="primary" @click="searchUser()">
                                搜索
                            </a-button>
                        </a-col>
                        <a-col :span="2" :offset="1">
                            <a-button @click="handleReset()">
                                重置
                            </a-button>
                        </a-col>
                    </a-row>
                </a-form>
            </a-card>

        </div>
        <a-table :columns="columns" :data-source="data" bordered style="margin-top: 20px">
            <template v-for="col in ['name', 'age', 'phoneNumber', 'user']" :slot="col" slot-scope="text, record">
                <div :key="col">
                    <a-input v-if="record.editable" style="margin: -5px 0" :value="text"
                        @change="e => handleChange(e.target.value, record.key, col)" />
                    <template v-else>
                        {{ text }}
                    </template>
                </div>
            </template>
            <template slot="avatar">
                <a-avatar shape="square" :size="64" icon="user" />
            </template>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <span v-if="record.editable">
                        <a @click="() => save(record.key)">Save</a>
                        <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
                            <a>Cancel</a>
                        </a-popconfirm>
                    </span>
                    <span v-else>
                        <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
                    </span>
                    <span style="display: inline-block; margin-left: 20px;">
                        <a :disabled="editingKey !== ''" @click="() => del(record.key)">删除</a>
                    </span>
                </div>
            </template>
        </a-table>
    </div>
</template>

<script>
import { addUser } from '@/services/user'
const columns = [
    {
        title: '姓名',
        dataIndex: 'name',
        width: '15%',
        scopedSlots: { customRender: 'name' },
    },
    {
        title: '年龄',
        dataIndex: 'age',
        width: '5%',
        scopedSlots: { customRender: 'age' },
    },
    {
        title: '手机号',
        dataIndex: 'phoneNumber',
        width: '15%',
        scopedSlots: { customRender: 'phoneNumber' },
    },
    {
        title: '身份',
        dataIndex: 'user',
        width: '10%',
        scopedSlots: { customRender: 'user' },
    },
    {
        title: '个人介绍',
        dataIndex: 'content',
        align: 'center',
        width: '15%',
        scopedSlots: { customRender: 'content' },
    },
    {
        title: '头像',
        dataIndex: 'avatar',
        width: '20%',
        scopedSlots: { customRender: 'avatar' },
        align: 'center',
    },
    {
        title: 'operation',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' },

    },
];

const data = [];
for (let i = 0; i < 100; i++) {
    data.push({
        key: i.toString(),
        name: `Edrward ${i}`,
        age: 32,
        address: `London Park no. ${i}`,
    });
}
import { mapState } from 'vuex'

export default {
    name: 'Demo',
    i18n: require('./i18n'),
    data() {
        this.cacheData = data.map(item => ({ ...item }));
        return {
            data,
            visible: false,
            columns,
            editingKey: '',
            userSearch: {},
            user: this.$form.createForm(this, { name: 'coordinated' }),
            loading: false,
            imageUrl: '',
            search:this.$form.createForm(this, { name: 'advanced_search' }),
        }
    },
    methods: {
        handleReset(){
            this.userSearch.name = ''
            this.userSearch.role = ''
        },
        searchUser(){
            console.log(this.userSearch);
        },
        avatarChange(info) {
            if (info.file.status === 'uploading') {
                this.loading = true;
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                // getBase64(info.file.originFileObj, imageUrl => {
                //     this.imageUrl = imageUrl;
                //     this.loading = false;
                // });
            }
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('You can only upload JPG file!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('Image must smaller than 2MB!');
            }
            return isJpgOrPng && isLt2M;
        },
        handleCancel() {
            this.visible = false
        },

        ChangeIdentity(e) {
            console.log(e);
        },
        handleOk() {
            this.user.validateFields((err) => {
                if (!err) {
                    this.visible = false
                    addUser(this.user).then(res => {
                        console.log(res);
                    })
                }
            });
        },
        handleChange(value, key, column) {
            const newData = [...this.data];
            const target = newData.find(item => key === item.key);
            if (target) {
                target[column] = value;
                this.data = newData;
            }
        },
        edit(key) {
            const newData = [...this.data];
            const target = newData.find(item => key === item.key);
            this.editingKey = key;
            if (target) {
                target.editable = true;
                this.data = newData;
            }
        },
        save(key) {
            const newData = [...this.data];
            const newCacheData = [...this.cacheData];
            const target = newData.find(item => key === item.key);
            const targetCache = newCacheData.find(item => key === item.key);
            if (target && targetCache) {
                delete target.editable;
                this.data = newData;
                Object.assign(targetCache, target);
                this.cacheData = newCacheData;
            }
            this.editingKey = '';
        },
        cancel(key) {
            const newData = [...this.data];
            const target = newData.find(item => key === item.key);
            this.editingKey = '';
            if (target) {
                Object.assign(target, this.cacheData.find(item => key === item.key));
                delete target.editable;
                this.data = newData;
            }
        },
    },
    computed: {
        ...mapState('setting', ['pageMinHeight']),
        desc() {
            return this.$t('description')
        }
    }
}
</script>

<style scoped lang="less">
@import "index";
</style>